<template>
  <div>
    <div
      id="requestTimeChart"
      style="width: 45vw; height: 35vh; margin-top: 20px"
    ></div>
  </div>
</template>

<script setup>
import * as echarts from 'echarts';
import { watch, ref } from 'vue';
const props = defineProps({
  chartsData: {
    type: Object,
    default: () => {},
  },
  // avgColors:{
  //   type: Array,
  //   default: () => [],
  // }
});
const seriesConfig = ref(null);
const newChartsData = ref({});
const legendArr = ref([]);
watch(
  () => props.chartsData,
  (newValue) => {
    if (newValue) {
      newChartsData.value = newValue;
      // 清空 legendArr 并重新填充
      legendArr.value = Object.keys(newChartsData.value.average.series);
      // 创建 series 配置项数组
      seriesConfig.value = legendArr.value.map((key, index) => ({
        name: key,
        type: 'line',
        symbolSize: 0,
        data: newChartsData.value.average.series[key],
        itemStyle: {
          color:
            newChartsData.value.average.colors[
              index % newChartsData.value.average.colors.length
            ],
        },
      }));
      // 调用处理函数更新图表
      handleBarChart();
    }
  }
);

const handleBarChart = () => {
  let chartDom = document.getElementById('requestTimeChart');
  let myChart = echarts.init(chartDom);
  let option;

  option = {
    // title: {
    //   text: newChartsData.value.users.title,
    // },
    tooltip: {
      trigger: 'axis',
    },
    legend: {
      data: legendArr.value,
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true,
    },
    //   toolbox: {
    //     feature: {
    //       saveAsImage: {},
    //     },
    //   },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: newChartsData.value.average.xAxis,
    },
    yAxis: {
      type: 'value',
    },
    series: seriesConfig.value,
  };

  option && myChart.setOption(option);
};
</script>

<style lang="scss" scoped></style>
